package com.ycsj.goldmedalnewconcept.parent.activity;

import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.PickerManager;
import com.ycsj.common.utils.DateUtils;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.MaxTextLengthFilter;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 在线请假
 */

public class ParentsLeaveOnlineActivity extends BaseActivity {

    //返回
    @BindView(R.id.iv_back)
    ImageView ivBack;

    //标题
    @BindView(R.id.tv_title)
    TextView tvTitle;

    //开始时间
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    //结束时间
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;

    //输入框
    @BindView(R.id.et_input)
    EditText etInput;

    //显示输入框的文字
    @BindView(R.id.tv_num)
    TextView tvNum;

    //请假次数详情
    @BindView(R.id.tv_details)
    TextView tvDetails;

    //提交
    @BindView(R.id.bt_commit)
    Button btCommit;

    //记录选择的起始时间
    private String stratTime, endTime;

    //请求参数
    private String acc, role, apptoken;


    //记录已批准次数和待批准次数
    private String approval, approvalPending;

    public static final String APPROVAL = "approval";

    public static final String APPROVALPENDING = "approvalPending";

    @Override
    protected int getContentLayout() {
        return R.layout.parent_activity_leave_new_online;
    }

    @Override
    protected void init() {
        initStateBar();

        //初始化标题
        initTitle();

        //获取传递的数据
        initIntent();


        //初始化请求参数
        initParams();

        //设置监听
        initListener();
    }


    /**
     * 初始化标题
     */
    private void initTitle() {
        tvTitle.setText("在线请假");
    }


    /**
     * 获取传递的数据
     */
    private void initIntent() {
        approval = getIntent().getStringExtra(APPROVAL);
        approvalPending = getIntent().getStringExtra(APPROVALPENDING);

        //设置已经批准或者待批准的次数
        if (!TextUtils.isEmpty(approval) && !TextUtils.isEmpty(approvalPending)) {
            tvDetails.setText("已批准 " + approval + " 次," + "待批准 " + approvalPending + " 次");
        } else if (TextUtils.isEmpty(approval) && !TextUtils.isEmpty(approvalPending)) {
            tvDetails.setText("已批准 " + 0 + " 次," + "待批准 " + approvalPending + " 次");
        } else if (TextUtils.isEmpty(approval) && TextUtils.isEmpty(approvalPending)) {
            tvDetails.setText("已批准 " + 0 + " 次," + "待批准 " + 0 + " 次");
        } else if (!TextUtils.isEmpty(approval) && TextUtils.isEmpty(approvalPending)) {
            tvDetails.setText("已批准 " + approval + " 次," + "待批准 " + 0 + " 次");
        }
    }


    /**
     * 请求参数
     */
    private void initParams() {
        acc = AccountUtils.getAccount(this);
        role = AccountUtils.getRole(this);
        apptoken = AccountUtils.getToken(this);
    }


    /**
     * 设置监听
     */
    private void initListener() {
        etInput.setFilters(new InputFilter[]{new MaxTextLengthFilter(201)});
        etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String content = etInput.getText().toString().trim();

                if (TextUtils.isEmpty(stratTime) || TextUtils.isEmpty(endTime)) {
                    //表示还没有选择开始时间和结束时间
                    btCommit.setBackgroundResource(R.drawable.parent_uncommit);
                    btCommit.setEnabled(false);
                } else {
                    if (TextUtils.isEmpty(content)) {
                        btCommit.setBackgroundResource(R.drawable.parent_uncommit);
                        btCommit.setEnabled(false);
                    } else {
                        btCommit.setBackgroundResource(R.drawable.parent_commit);
                        btCommit.setEnabled(true);
                    }
                }

                if (!TextUtils.isEmpty(content)) {
                    if (content.length() > 199) {
                        tvNum.setText("200/200");
                    } else {
                        tvNum.setText(content.length() + "/200");
                    }
                } else {
                    tvNum.setText("0/200");
                }
            }
        });
    }


    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @OnClick({R.id.iv_back, R.id.tv_start_time, R.id.tv_end_time, R.id.bt_commit})
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.tv_start_time) {
            //开始时间
            showChooseTimePicker(1);
        } else if (id == R.id.tv_end_time) {
            //结束时间
            showChooseTimePicker(2);
        } else if (id == R.id.bt_commit) {
            //提交
            doCommitAction();
        }
    }


    /**
     * 提交的操作
     */
    private void doCommitAction() {
        //先判断是否选择了开始时间和结束时间
        if (TextUtils.isEmpty(stratTime)) {
            ToastUtils.showShort("请选择开始时间");
            return;
        }

        if (TextUtils.isEmpty(endTime)) {
            ToastUtils.showShort("请选择结束时间");
            return;
        }

        //判断结束时间是否大于开始时间
        if (DateUtils.getTime(endTime, "yyyy-MM-dd") < DateUtils.getTime(stratTime, "yyyy-MM-dd")) {
            ToastUtils.showShort("请假的结束时间必须大于开始时间");
            return;
        }


        //获取请假事由
        final String reason = etInput.getText().toString().trim();

        if (TextUtils.isEmpty(reason)) {
            //
            ToastUtils.showShort("请输入请假事由");
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put("type", "2");
        map.put("acc", acc);
        map.put("role", role);
        map.put("apptoken", apptoken);
        map.put("platform", "2");
        map.put("content", reason);
        map.put("begindate", stratTime);
        map.put("enddate", endTime);

        CustomDialogManager.show(this, "提交中...");

        HttpUtils.post(HttpAddress.LEAVEONLINE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                ToastUtils.showShort(BaseApplication.ERROR);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                LogUtils.iTag("test", reason);
                if (!TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if ("200".equals(info.state) || "102002".equals(info.state)) {
                            //发送请假列表更新的消息
                            BusInfo busInfo = new BusInfo();
                            busInfo.msg = ParentsLeaveListActivity.LEAVEONLINE;
                            EventBus.getDefault().post(busInfo);
                            ToastUtils.showShort("已完成请假，请耐心等待老师批假吧");
                            //返回成功
                            finish();

                        } else {
                            ToastUtils.showShort("提交失败,返回错误码:" + info.state);
                            Log.i("test", "返回器返回异常,错误码是:" + info.state);
                        }
                    }
                } else {
                    Log.i("test", "服务返回数据异常");
                }
            }
        });
    }

    /**
     * 时间选择器
     */
    private void showChooseTimePicker(final int type) {
        PickerManager.showPickerByYeaerAndMonthAndDayAndHourWithLimit(this, new PickerManager.onSelectedListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                //获取输入框的内容
                String content = etInput.getText().toString().trim();
                if (type == 1) {
                    //记录选择的开始时间
                    stratTime = DateUtils.getTime(date, "yyyy-MM-dd");
                    tvStartTime.setText(DateUtils.getTime(date, "yyyy年-MM月-dd日"));

                    if (TextUtils.isEmpty(endTime) || TextUtils.isEmpty(content)) {
                        btCommit.setBackgroundResource(R.drawable.parent_uncommit);
                        btCommit.setEnabled(false);
                    } else {
                        btCommit.setBackgroundResource(R.drawable.parent_commit);
                        btCommit.setEnabled(true);
                    }

                } else if (type == 2) {

                    endTime = DateUtils.getTime(date, "yyyy-MM-dd");
                    tvEndTime.setText(DateUtils.getTime(date, "yyyy年-MM月-dd日"));

                    if (TextUtils.isEmpty(stratTime) || TextUtils.isEmpty(content)) {
                        btCommit.setBackgroundResource(R.drawable.parent_uncommit);
                        btCommit.setEnabled(false);
                    } else {
                        btCommit.setBackgroundResource(R.drawable.parent_commit);
                        btCommit.setEnabled(true);
                    }

                }
            }
        });
    }
}
